package com.qf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * projectName:temp_shop
 * author:luo
 * time:2023/3/15 20:18
 * 防止消息被重复消费
 */
@Component
public class MessageRetryCustomListener {
//    @Autowired
//    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//值类型
    /**
     *  * 防止消息被重复消费
     */
    @RabbitListener(queues = "queue_c1")
    public void rQ1(String msg, Message message, Channel channel)throws Exception{
        //1:假设有id
        String id = (String) message.getMessageProperties().getHeaders().get("spring_listener_return_correlation");

        //String id="";//8f7485ce-51e1-498c-a9a8-1692b71a5cb9
        //1:判断当前消息是否正在被消费

        message.getMessageProperties().getDeliveryTag();
        Boolean isFlag = stringRedisTemplate.opsForValue().setIfAbsent(id, "0");
        if (isFlag){
            //未消费 白上锁了  由我来消费
            System.out.println("==消费了==");
            stringRedisTemplate.opsForValue().set(id, "1");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            //被消费了 0刚刚在消费 1消费完成
            String value = stringRedisTemplate.opsForValue().get(id);
            //发生网络波动
            if (StringUtils.isEmpty(id)&&"0".equals(value)){
                //啥也不干
            }else {
                //帮它应答
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }

    }
}
